//
//  HLSettingViewController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/8/31.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLSettingViewController.h"
#import "MBProgressHUD+HL.h"
#import "HLDataBaseManager.h"
#import "HLTabBarViewController.h"
#import "HLNavigationController.h"
#import "HLLoginViewController.h"
#import "HLIderFeedBackController.h"
#import "HLDataBaseManager.h"

@interface HLSettingViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic , strong) UITableView * tableView ;

@end

@implementation HLSettingViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setUI];
}

- (NSArray *)titles
{
    return @[@[@"允许2G/3G/4G环境下下载资源",@"关于我们",@"清除缓存",@"清除历史记录"],@[@"当前版本",@"意见反馈"]];
}

- (void)setUI
{
    self.navigationItem.title = @"设置";
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight ) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:self.tableView];
    
    [self setBottomButton];
}

- (void)setBottomButton
{
    CGFloat buttonH = IS_IPHONE_5 ? 35 : 40;
    UIButton *loginout = [UIButton buttonWithType:UIButtonTypeCustom];
    loginout.frame = CGRectMake(10, ScreenHeight - buttonH - 5, ScreenWidth - 20, buttonH);
    [loginout setTitle:@"退出账号" forState:UIControlStateNormal];
    [loginout setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginout addTarget:self action:@selector(loginout) forControlEvents:UIControlEventTouchUpInside];
    loginout.titleLabel.font = [UIFont systemFontOfSize:15];
    loginout.backgroundColor = kColorMineBlueBG;
    loginout.layer.cornerRadius = buttonH *0.5;
    loginout.clipsToBounds = YES;
    [self.view addSubview:loginout];
    self.view.backgroundColor = HLRGB(245, 245, 245);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section == 0 ? 4 : 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ccellIdentifier"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:1 reuseIdentifier:@"ccellIdentifier"];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = kColorMainTitle;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.row == 0 && indexPath.section == 0) {
        UISwitch *s = [[UISwitch alloc] init];
        s.on = [HLReadForLocation(kHLSettingAllow4GDownloadSource) isEqualToString:@"YES"];
        [s addTarget:self action:@selector(netSwitchChange:) forControlEvents:UIControlEventValueChanged];
        cell.accessoryView = s;
    }
    if (indexPath.row == 2) {
        [self setupFileSizeInCell:cell];
    }
    if (indexPath.section == 1 &&indexPath.row == 0) {
        cell.detailTextLabel.text = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    if (indexPath.section == 1 &&indexPath.row == 1) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.imageView.backgroundColor = [UIColor redColor];
    cell.textLabel.text = [self titles][indexPath.section][indexPath.row];
    [tableView addLineforPlainCell:cell forRowAtIndexPath:indexPath withLeftSpace:0];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 2){
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除缓存会清空下载的视频和文件" message:nil preferredStyle:UIAlertControllerStyleAlert];
        __weak typeof(self)weakSelf = self;
        [alertController addAction:[UIAlertAction actionWithTitle:@"想好了" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [MBProgressHUD show];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [weakSelf clearCacheInCell:cell];
            });
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    if (indexPath.row == 1 && indexPath.section == 0) {
        NSLog(@"关于我们");
    }
    if (indexPath.row == 3 && indexPath.section == 0) {
        [MBProgressHUD show];
        [HLDataBaseManager removeALLHistoryRecord];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showSuccessMessage:@"清除成功"];
        });
    }
    if (indexPath.row == 1 && indexPath.section == 1) {
        [self ideaFeedBack];
    }
    
}

- (void)ideaFeedBack
{
    HLIderFeedBackController *ideaFeedback = [[HLIderFeedBackController alloc] init];
    ideaFeedback.title = @"意见反馈";
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:ideaFeedback];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)setupFileSizeInCell:(UITableViewCell *)cell
{
    /**** 禁止点击事件 ****/
    cell.userInteractionEnabled = NO;
    cell.accessoryType = UITableViewCellAccessoryNone;
    // 右边显示圈圈
    UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [loadingView startAnimating];
    cell.accessoryView = loadingView;

    /****  计算大小  ****/
    [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
        /*** 计算缓存大小 ***/
        NSInteger size = HLCacheFile.fileSize;
        CGFloat unit = 1000.0;
        NSString *sizeText = nil;
        if (size >= unit * unit * unit) { // >= 1GB
            sizeText = [NSString stringWithFormat:@"%.1fGB", size / unit / unit / unit];
        } else if (size >= unit * unit) { // >= 1MB
            sizeText = [NSString stringWithFormat:@"%.1fMB", size / unit / unit];
        } else if (size >= unit) { // >= 1KB
            sizeText = [NSString stringWithFormat:@"%.1fKB", size / unit];
        } else { // >= 0B
            sizeText = [NSString stringWithFormat:@"%zdB", size];
        }
        NSString *text = [NSString stringWithFormat:@"%@", sizeText];
        
        /****回到主线程 ****/
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            cell.detailTextLabel.text = text;
            cell.accessoryView = nil;
            /**** 允许点击事件 ****/
            cell.userInteractionEnabled = YES;
        }];
    }];
}

- (void)clearCacheInCell:(UITableViewCell *)cell
{
    [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
        
        [HLDataBaseManager removeALLDownloadedFile];
        [HLDataBaseManager removeALLDownloadingFile];
        [[NSFileManager defaultManager] removeItemAtPath:NSHomeDirectory() error:nil];
        [[NSFileManager defaultManager] removeItemAtPath:HLCacheFile error:nil];
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showSuccessMessage:@"清除成功"];
            cell.detailTextLabel.text = @"0B";
            /**** 禁止点击事件 ****/
            cell.userInteractionEnabled = YES;
                   }];
    }];
}

- (void)netSwitchChange:(UISwitch*)netSwitch
{
    if (netSwitch.isOn) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"2G/3G/4G环境下下载会消耗流量,确定使用?"message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            HLWriteForLocation((netSwitch.isOn ?@"YES" : @"NO"), kHLSettingAllow4GDownloadSource);
            HLWriteLocation;
            
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            netSwitch.on = NO;
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        HLWriteForLocation((netSwitch.isOn ?@"YES" : @"NO"), kHLSettingAllow4GDownloadSource);
        HLWriteLocation;
    }
}

- (void)loginout
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"message:@"真的要退出登录吗?" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        /**** 退出登录 ****/
        // 设置根控制器
        HLNavigationController *loginNav = [[HLNavigationController alloc]initWithRootViewController:[HLLoginViewController new]];
        kKeyWindow.rootViewController = loginNav;
       
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}


@end
